var app = null;
//图片上传
var maxCount = 6;

//清空用户输入数据
function clearUserInput(){
    app.itemName = '';
    app.itemCompany = '';
    app.itemUser1 ='';
    app.itemDepartment = '';
    app.user1Phone = '';
    app.itemText = '';
    app.itemUser2 = '';
    app.user2Department = '';
    app.user2Phone = '';
    app.user2Text = '';
    app.itemUser3 = '';
    app.user3Department = '';
    app.user3Phone = '';
    app.user3Text = '';
    app.itemFile = '';
    app.imgArr = [];

    //清除页面图片
    document.querySelector('.weui_uploader_files').innerHTML = '';
    var num = $('.weui_uploader_file').length;  
    $('.js_counter').text(num + '/' + maxCount);
    $('.weui_uploader_input_wrp').show();
}

mui.ready(function(){
    //初始化局部滚动控件
    mui('.mui-scroll-wrapper').scroll({
        indicators: true //是否显示滚动条
    });

    //初始化vue实例
    app = new Vue({
        el:'#app',
        data:{
            itemType : 0, //项目类型 0：单一项目 1：系统性项目

            itemName : '', //项目名
            itemCompany : '', //所属单位
            itemUser1 : '', //项目负责人
            itemDepartment : '', //部门
            user1Phone : '', //负责人电话
            itemText : '', //项目内容

            itemUser2 : '', //官方对接人
            user2Department : '', //官方对接人单位
            user2Phone : '', //官方对接人电话
            user2Text : '', //官方对接人内容

            itemUser3 : '', //中间对接人
            user3Department : '', //中间对接人单位
            user3Phone : '', //中间对接人电话
            user3Text : '', //中间对接人内容

            itemFile : '', //项目相关文件内容
            imgArr : []
        },
        methods:{
            handleSubmit:function(){  //数据提交
                //判断必填数据是否为空
                if( this.itemName == '' ){
                    mui.toast('请输入项目名称');
                    return;
                }
                if( this.itemCompany == '' ){
                    mui.toast('请输入所属单位');
                    return;
                }
                if( this.itemUser1 == '' ){
                    mui.toast('请输入项目负责人');
                    return;
                }
                if( this.itemDepartment == '' ){
                    mui.toast('请输入项目负责人部门');
                    return;
                }
                if( this.user1Phone == '' ){
                    mui.toast('请输入项目负责人联系方式');
                    return;
                }
                if( this.itemText == '' ){
                    mui.toast('请输入项目内容');
                    return;
                }
                var imgBaseStr = '';
                //判断图片是否存在
                if( this.imgArr.length > 0 ){
                    imgBaseStr = (this.imgArr).join('★');
                }
                var self = this;
                jQuery.ajax({
                    url:OPENAPI.insertItem,
                    data:{
                        itemType : self.itemType,
                        itemName : self.itemName,
                        itemCompany : self.itemCompany,
                        itemUser1 : self.itemUser1,
                        itemDepartment : self.itemDepartment,
                        user1Phone : self.user1Phone,
                        itemText : self.itemText,
                        itemUser2 : self.itemUser2,
                        user2Department : self.user2Department,
                        user2Phone : self.user2Phone,
                        user2Text : self.user2Text,
                        itemUser3 : self.itemUser3,
                        user3Department : self.user3Department,
                        user3Phone : self.user3Phone,
                        user3Text : self.user3Text,
                        itemFile : self.itemFile,
                        itemImg : imgBaseStr
                    },
                    dataType:'json',
                    type:'post',
                    timeout:5000,
                    success:function(data){
                        if( data.result == 1 ){
                            mui.toast('提交成功');
                            //清空用户输入
                            clearUserInput();
                        }else{
                            mui.toast('网络连接异常');
                        }

                    },
                    error:function(error){
                        mui.toast('网络连接异常');
                    }
                });
            },
            handleBlur:function(event){ //验证用户是否输入的数字
                if( isNaN( Number( event.target.value ) ) ){  //当输入不是数字的时候，Number后返回的值是NaN;然后用isNaN判断。
                    mui.toast('联系方式格式不正确');
                    event.target.value = '';
                }
            }
        }
    });

    //保存图片内容
    app.imgArr = [];
    //图片上传
    var file = {
        upload: function (e) {					  						  	
            var self = this;
            var files = e.target.files;
            var type = files[0].type.split('/')[0];
            //判断用户上传的是否为图片
            if (type != 'image') {
                mui.toast('请上传图片');
                return;
            }
            //var size = Math.floor(file.size / 1024 / 1024);
            //if (size > 3) {
            //  alert('图片大小不得超过3M');
            //  return;
            //};
            for (var i = 0; i < files.length; i++) {
                var reader = new FileReader();
                reader.readAsDataURL(files[i]);
                reader.onloadstart = function () {
                    //用以在上传前加入一些事件或效果，如载入中...的动画效果
                };
                reader.onloadend = function (e) {
                    var dataURL = this.result;
                    var imaged = new Image();
                    imaged.src = dataURL;
                    //利用canvas对图片进行压缩
                    imaged.onload = function () {  
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        var w = 0;
                        var h = 0;
                        if (this.width > this.height) {
                            h = 1000;
                            var scale = this.width / this.height;
                            h = h > this.height ? this.height : h;
                            w = h * scale;
                        }
                        else {
                            w = 1000;
                            var scale = this.width / this.height;
                            w = w > this.width ? this.width : w
                            h = w / scale;
                        }
                        var anw = document.createAttribute("width");
                        var anh = document.createAttribute("height");
                        if (this.width > this.height) {
                            anw.value = h;
                            anh.value = w;
                        }
                        else {
                            anw.value = w;
                            anh.value = h;
                        }
                        canvas.setAttributeNode(anw);
                        canvas.setAttributeNode(anh);
                        if (this.width > this.height) {
                            ctx.translate(h, 0);
                            ctx.rotate(90 * Math.PI / 180)
                            ctx.drawImage(this, 0, 0, w, h);
                            ctx.restore();
                        }
                        else {
                            ctx.drawImage(this, 0, 0, w, h);
                        }
                        dataURL = canvas.toDataURL('image/jpeg');
                        app.imgArr.push(dataURL);
                        // 插入到预览区
                        var $preview = $('<li class="weui_uploader_file weui_uploader_status" style="position:relative;background-image:url(' + dataURL + ')"><div class="weui_uploader_status_content">0%</div></li>');
                        $('.weui_uploader_files').append($preview);
                        var num = $('.weui_uploader_file').length;                             
                        $('.js_counter').text(num + '/' + maxCount);
                        if(num>=maxCount){
                            $('.weui_uploader_input_wrp').hide();
                        }
                        // 然后假装在上传，可以post base64格式，也可以构造blob对象上传，也可以用微信JSSDK上传
                        var progress = 0;
                        function uploading() {
                            $preview.find('.weui_uploader_status_content').text(++progress + '%');
                            if (progress < 100) {
                                setTimeout(uploading, 30);
                            }
                            else {
                                // 如果是失败，塞一个失败图标
                                //$preview.find('.weui_uploader_status_content').html('<i class="weui_icon_warn"></i>');
                                $preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();
                            }
                        }  
                        setTimeout(uploading, 30);
                    };
                };
            }
        },
        event: function () {
            $("#upload").change(function (e) {      
                file.upload(e);
            });
        },
        init: function () {
            this.event(); 
        }
    }
    file.init();
    //图片删除事件
    mui('.weui_uploader_files').on('tap','li',function(){	
        var that  = this;
        var btnArray = ['否', '是'];
        mui.confirm('确定要删除吗？', '提示', btnArray, function(e){
            if (e.index == 1) {
                //确认删除后，判断删除节点所在位置
                var imgList = document.querySelectorAll('.weui_uploader_file');
                var delIndex = -1;
                Array.prototype.forEach.call(imgList,function(item,index,arr){
                    if( that == item ){
                        delIndex = index;
                    }
                });
                jQuery(that).remove();
                app.imgArr.splice(delIndex,1);
                var num = $('.weui_uploader_file').length;  
                $('.js_counter').text(num + '/' + maxCount);
                $('.weui_uploader_input_wrp').show();
            }
        })
    });
});
